# -*- coding: utf-8 -*
import re

from .enums import PastTime, DateTailPointer
from typing import List


def handle_standard_time(raw_time: str, past_time: PastTime) -> str:
    """将ISO时间戳转换为InfluxDB标准的查询时间戳"""
    if not isinstance(past_time, PastTime):
        raise TypeError("Type of past_time must be 'PastTime'!")

    stan_time = raw_time.split('.')[0] + 'Z'
    past_time: str = past_time.value

    unit_pat = re.compile(r'[smh]$')
    num_pat = re.compile(r'^\d+')
    unit = unit_pat.search(past_time).group()
    num = int(num_pat.search(past_time).group())

    date: List[str] = stan_time.split('T')
    date[1] = date[1][:-1]  # 去除后缀Z
    yhd: List[int] = list(map(int, date[0].split('-')))
    hms: List[int] = list(map(int, date[1].split(':')))

    hour, minute, second = hms[0], hms[1], hms[2]

    # TODO: 还需要考虑一下每月30天或31天的问题
    def reset(date: List[int], num: int, tp: int) -> List[int]:
        """用于解决日期换算发生借位的问题"""
        base = {
            'SEC': 60,
            'MIN': 60,
            'HOUR': 24,
            'DAY': 30,
            'MONTH': 12,
        }
        pos = ['MONTH', 'DAY', 'HOUR', 'MIN', 'SEC']

        date[tp] = date[tp] + base[pos[tp]] - num
        tp = tp - 1
        if ((tp == -2 or tp == -3) and date[tp] - num < 0) or ((tp < -3) and date[tp] - num <= 0):
            date = reset(date, 1, tp)
        else:
            date[tp] = date[tp] - num

        return date

    all_date: List[int] = []
    all_date.extend(yhd)
    all_date.extend(hms)
    if unit == 's':
        if second >= num:
            all_date[DateTailPointer.SEC.value] = second - num
        else:
            all_date = reset(all_date, num, DateTailPointer.SEC.value)
    elif unit == 'm':
        if minute >= num:
            all_date[DateTailPointer.MIN.value] = minute - num
        else:
            all_date = reset(all_date, num, DateTailPointer.MIN.value)
    elif unit == 'h':
        if hour >= num:
            all_date[DateTailPointer.HOUR.value] = hour - num
        else:
            all_date = reset(all_date, num, DateTailPointer.HOUR.value)

    def fill_prefix_zero(raw: str) -> str:
        """补充前导0"""
        new = raw
        if len(raw) < 2:
            new = '0' + new
        return new

    all_date: List[str] = list(map(fill_prefix_zero, map(str, all_date)))
    return "-".join(all_date[:3]) + "T" + ":".join(all_date[-3:]) + "Z"
